package com.rpframework.module.common.bottom.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rpframework.core.json.EmptyException;
import com.rpframework.core.json.JsonResp;
import com.rpframework.module.common.bottom.entity.enums.RequestType;
import com.rpframework.module.common.bottom.service.TokenService;
import com.rpframework.module.common.bottom.weixin.JSsignature;
import com.rpframework.module.common.bottom.weixin.util.Sha1Util;
import com.rpframework.module.common.bottom.weixin.util.WeiXinSignAndPackage;
import com.rpframework.module.common.config.WeixinConfig;
import com.rpframework.module.common.springmvc.annotation.AutoMapping;
import com.rpframework.module.common.url.RequestDescription;
/**
 * JS-JDK接口
 * 
 * @author qiuchengbing
 *
 */
@ResponseBody
@RequestMapping
@RequestDescription("微信js-jdk签名")
@Controller
@AutoMapping(RequestType.WX_CALLBACK)
public class JsJdkController {
	@Autowired
	private TokenService tokenService;
	@Autowired(required = false)
	private WeixinConfig weixinConfig;

	/**
	 * 
	 * JS-JDK签名认证
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/photograph")
	@ResponseBody
	public JsonResp<?> Photograph(HttpServletRequest request) {
		String appId = weixinConfig.getAppId();
		String url = request.getParameter("url");
		if (StringUtils.isBlank(url)) {
			// 获取请求链接地址为空
			 throw new EmptyException("获取请求链接地址为空！");
		}
		String jsapi_ticket = tokenService.findTicket(appId);
		if (StringUtils.isBlank(jsapi_ticket)) {
			// 获取签名错误
			 throw new EmptyException("获取微信签名错误！");
		}
		String nonceStr = Sha1Util.getNonceStr();// 随机字符串
		String timestamp = Sha1Util.getTimeStamp();// 时间戳
		try {
			url = URLDecoder.decode(url, "UTF-8");// 获取的动态地址
		} catch (UnsupportedEncodingException e) {
			 throw new EmptyException("请求链接地址编码异常！");
		}
		TreeMap<String, String> treeMap = new TreeMap<String, String>();
		treeMap.put("url", url); // 请求地址
		treeMap.put("noncestr", nonceStr); // 随机字符串
		treeMap.put("jsapi_ticket", jsapi_ticket); // 有效验证
		treeMap.put("timestamp", timestamp); // 时间戳
		String signature = WeiXinSignAndPackage.originalString(treeMap);// 拼接JDK签名
		if (StringUtils.isBlank(signature)) {
			// 前面失败
			throw new EmptyException("签名失败！");
		}
		JSsignature data = new JSsignature();
		data.setAppId(appId);
		data.setNonceStr(nonceStr);
		data.setSignature(signature);
		data.setTimestamp(timestamp);
		return new JsonResp<>().succ("创建成功",data);
	}
}